import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnInit,
  Output,
  ViewChild,
} from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { GridOptions } from '@ag-grid-community/core';
import { ApiService } from '../../core/services/http/api.service';
import { GridConfigService } from '../../core/config/grid-config.service';
import { ApesModalRef } from '../apes/modal/index';
import {
  agCurrency, agNumber,
  dateFormat, deepClone,
  exists, getO,
  getText,
  getValueUsingField,
  replaceAll,
  type,
} from '../../utils/utils';
import { ApesMessageService } from '@shared/apes/message';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { UserAuthService } from '@core/services/user-auth.service';
import { toBoolean } from '@shared/apes/core';
import { ApesRenderPopoverComponent } from '@shared/ag-grid-ext/cell-renders/render-popover.component';
import { ApesLoadingOverlayComponent } from '@shared/ag-grid-ext/loading-overlay/apes-loading-overlay.component';
import { FormService } from '@core/services/form.service';
import { SubjectService } from '@core/services/events/subject.service';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { CustomHeaderComponent } from '@shared/ag-grid-ext/header-component/custom-header.component';
import { RenderTooltipComponent } from '@shared/ag-grid-ext/cell-renders/render-tooltip.component';
import { RenderOperatingButtonComponent } from '@shared/ag-grid-ext/cell-renders/render-operating-button.component';
import { RenderButtonComponent } from '@shared/ag-grid-ext/cell-renders/render-button.component';
import { ShowHiddenHeaderComponent } from '@shared/ag-grid-ext/header-component/showHidden-header.component';
import { RenderShowHiddenComponent } from '@shared/ag-grid-ext/cell-renders/render-showHidden.component';

@Component({
  selector: 'apes-base-dialog',
  templateUrl: './apes-dialog.component.html',
  styles: [`

  `],
})
export class ApesDialogComponent implements OnInit, AfterViewInit {
  public modules: Module[] = AllModules;
  private searchDebounce = 300;
  private searchSubject = new Subject<string>();
  agGrid: any;
  prefixCls = 'apes-base-dialog';
  // 分页器
  total = 0;
  loadingTotal = 0;
  pageSize = 20;
  currentPage = 1;
  pageTotal = 0;

  rowData: any[];
  resultData: any = '';
  resultsData: any[] = [];
  loading: any = false;
  searchLoading = false; // 搜索按钮的动画
  gridOptions: GridOptions;
  frameworkComponents;
  loadingOverlayComponent;
  private gridApi;
  private gridColumnApi;
  conditionRequired = false; // 查询条件是否必须

  // form 定义相关
  form: FormGroup;
  model: any = {};
  options: any = {};
  ctx: any = {};
  tableValid = {};
  /**订阅主题**/
  subjects = {};

  filterType: boolean = false; // 用于显示侧边过滤条件
  filterConditionField: any[] = [];  // 侧边查询条件

  // 用于改造纯查询控件
  @Input() pureSearch: boolean = false;

  @Input() title: '';
  @Input() conditionField: any[] = [];  // 查询条件
  showConditionField: any[] = [];  // 查询条件
  @Input() api = '';    // 查询接口地址
  @Input() columnDefs: any[];     // grid 列头定义
  @Input() rowSelection: string;  // grid的选择模式 multiple  or single
  @Input() domain: any;
  @Input() apiParams: any; // api默认条件
  @Input() autoQuery: any; // 自动查询
  @Input() treeData: any;
  @Input() secondaryApi = '';

  @Input() conditionModel: any; // 主表数据
  @Input() gridData: any;  // 表格内数据
  @Input() addSame: boolean = true; // 允许选择相同
  // @Input() filterKey:any; // 过滤条件
  // @Input() showId: any;
  // @Input() showName: any;
  // @Input() showField: any[] = [];  // 显示字段
  @Input() uniqueKey: any = 'innerBusinessKey';    // 唯一字段
  @Input() valueFormatter: any;
  @Input() selectLastStage: any; /*不为空只能选择末级*/

  @Input() btnRemarks: any; // 用于重要提示
  @ViewChild('searchBox', { static: false }) searchBox: ElementRef;
  @Output() onSearch = this.searchSubject.pipe(distinctUntilChanged(), debounceTime(this.searchDebounce));
  @Output() onFocus = new EventEmitter<string>();

  @Input() pageSizeOptions: any[] = [];
  showSizeChanger: boolean = false;
  @Input() checkboxSelect: boolean = false;
  @Input() defaultCheckbox: boolean = false;
  suppressRowClickSelection: boolean = false;

  autoGroupColumnDef: any;
  rowModelType: any;
  showCondition: any;

  pagination = {
    currentPage: 0,
    lastRow: -1,
    pageSize: 20,
  };

  user: any;

  constructor(gridConfigService: GridConfigService,
              private apiService: ApiService,
              private  expressionService: ExpressionService,
              private msg: ApesMessageService,
              public modal: ApesModalRef,
              protected userService: UserAuthService,
              protected subject: SubjectService,
              protected formService: FormService,
  ) {

    this.gridOptions = <GridOptions>{};
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.frameworkComponents = {
      renderPopover: ApesRenderPopoverComponent,

      loadingOverly: ApesLoadingOverlayComponent,
      customHeader: CustomHeaderComponent,
      renderTooltip: RenderTooltipComponent,
      button: RenderButtonComponent,
      showHiddenHeader: ShowHiddenHeaderComponent,
      renderShowHidden: RenderShowHiddenComponent,
      // dialogButton: RenderOperatingButtonComponent 无法添加按钮栏
    };
    this.loadingOverlayComponent = 'loadingOverly';
    /**拉模型：组件创建时初始化**/
    this.userService.getUser().subscribe(user => {
      this.user = user;
      this.ctx.user = this.user;
    });

    /**推模型：数据变更时主动触发**/
    this.userService.userSubject.subscribe(user => {
      this.user = user;
      this.ctx.user = this.user;
    });
  }

  /**
   * 功能：初始化上下文环境变量
   */
  private initContext() {
    this.model = { ...this.apiParams };
    this.ctx.model = this.model;
    this.ctx.form = this.form;
    this.ctx.user = this.user;
    this.ctx.subjects = this.subjects;
    this.ctx.states = 'submit';
    this.options.formState = this.ctx;
    this.ctx.platform = this.userService.getUserInfoObj() ? this.userService.getUserInfoObj().platform : ''; // 判断平台
    this.ctx['this'] = this;
  }


  ngOnInit() {
    this.form = new FormGroup({ quickSearchInput: new FormControl('') });
    this.initContext();

    this.rowModelType = 'clientSide';
    this.resetConditions(this.conditionField);

    this.pureSearch = this.pureSearch ? toBoolean(this.pureSearch) : false;
    if (this.pureSearch) return;

    if (this.defaultCheckbox) {
      let checkbox = {
        headerName: '',
        field: 'checkboxs',
        width: '50',
        checkboxSelection: true,
        pinned: 'left',
      };
      this.columnDefs.unshift(checkbox);
    }

    this.columnDefs.forEach(element => {
        if (element.field == 'rowIndex') {
          element.width = 70;
          element.cellRenderer = function(params) {
            return params.rowIndex + 1;
          };
        }
        if (element.hasOwnProperty('hideExpression')) {
          element.hide = this.expressionService.eval(element.hideExpression, {
            context: this.ctx,
            form: this.form,
          });
        }
        if (element.hasOwnProperty('changeCellStyle')) {
          let that = this;
          element.cellStyle = (params) => {
            let CellStyle = element['changeCellStyle'];
            let res = that.expressionService.eval(CellStyle, params);
            return res;
          };
        }

        if (element.hasOwnProperty('checkboxSelection')) {
          element.headerCheckboxSelectionFilteredOnly = true;
          element.headerCheckboxSelection = true;
          element.checkboxSelection = true;
        }

        if (element.buttonList) {
          let buttonList;
          buttonList = replaceAll(element.buttonList, '\'', '"');
          buttonList = replaceAll(buttonList, '`', '\'');
          buttonList = JSON.parse(buttonList);
          buttonList.forEach(btn => {
            let cellButtonListDisabled = btn.disabled || 'false';
            btn.disabled = this.expressionService.eval(cellButtonListDisabled, {
              context: this.ctx,
              form: this.form,
              model: this.ctx.model,
            });
          });
          element.buttonList = buttonList;
        }

        if (element.hasOwnProperty('valueFormatter')) {
          if (element.valueFormatter == 'currency') {
            element.valueFormatter = agCurrency;
          } else if (element.valueFormatter == 'number') {
            element.valueFormatter = agNumber;
            element['valueFormatterMeta'] = 'number';
          }
        }

      },
    );
    if (this.pageSizeOptions.length != 0) {
      this.pageSizeOptions = getO(this.pageSizeOptions);
      this.showSizeChanger = true;
    }

    if (this.treeData === 'true') {
      this.treeData = true;
      this.autoGroupColumnDef = {
        cellRendererParams: {
          innerRenderer: function(params) {
            return params.data.name;
          },
        },
      };
      this.rowModelType = 'clientSide';
      this.autoQuery = 'true';
      this.showCondition = this.conditionField.length > 0 ? true : false;
    } else if (this.checkboxSelect) {
      this.checkboxSelect = toBoolean(this.checkboxSelect);
      this.rowModelType = 'clientSide';
      this.suppressRowClickSelection = true;
      setTimeout(() => {
        this.gridApi.hideOverlay();
      }, 100);
    } else {
      this.rowModelType = 'serverSide'; //infinite
      this.gridOptions.infiniteInitialRowCount = 1;
      this.gridOptions.pagination = false;
      this.gridOptions.cacheBlockSize = 20;
      //this.gridOptions.maxBlocksInCache =100;
      this.gridOptions.paginationPageSize = this.pagination.pageSize;
    }
    this.searchSubject.pipe().subscribe(data => this.gridApi.setQuickFilter(data));

    this.subject.subscribe(this.ctx, 'changeShowType', data => {
      this.resetColumnDefs(this.columnDefs);
    });
  }

  resetConditions(conditions) {
    conditions.forEach(condition => {
      if (condition.key === 'state') {
        if (type(condition.defaultValue) === 'object') {
          condition.defaultValue = JSON.parse(condition.defaultValue);
        }
      } else if (type(condition.defaultValue) === 'string' && condition.defaultValue.indexOf('{{') > -1) {
        let text = getText(condition.defaultValue);
        let value = getValueUsingField(this.user, text, true);
        condition.defaultValue = value.id;
        condition.templateOptions.config.items = JSON.stringify([value]);
      }
      //if (missing(condition.templateOptions.divCol))
      condition.templateOptions.divCol = 12;

      if (condition.templateOptions.config.hasOwnProperty('filterType')) {
        this.filterType = true;
        this.filterConditionField.push(condition);
        condition.templateOptions.divCol = 24;
      }

    });
    if (this.filterType) {
      this.subject.subscribe(this.ctx, 'filterSelected', data => {
        // console.log(data);
        this._search();
      });
    }

    this.formService.extFormMetadata(conditions, this.ctx, this.subject, this.tableValid);
    this.showConditionField = this.showConditionField.concat(conditions);
    this.ctx.$showConditionField = this.showConditionField;
  }

  resetColumnDefs(columnDefs) {
    this.columnDefs = deepClone(columnDefs);
    this.columnDefs.forEach(element => {
        if (element.hasOwnProperty('hideExpression')) {
          element.hide = this.expressionService.eval(element.hideExpression, {
            context: this.ctx,
            form: this.form,
          });
        }
      },
    );

    let dataSource = {
      rowCount: null,
      getRows: (params: any) => {
        params.successCallback([], 0);
      },
    };
    //this.gridApi.setDatasource(dataSource);
    this.gridApi.setServerSideDatasource(dataSource);
  }

  ngAfterViewInit() {
    if (this.autoQuery) {
      setTimeout(() => {
        this._search();
      }, 100);
    }
  }

  private getRows(params: any, data: any, sendData: any) {
    sendData['size'] = this.pagination.pageSize;
    sendData['page'] = this.pagination.currentPage;
    // TODO 检查返回值是否不为空数组
    this.gridApi.showLoadingOverlay();
    this.apiService.post(this.api, { 'body': JSON.stringify(sendData) })
      .subscribe(items => {
        if (items) {
          this.total = items.total;
          const itemsLength = items.content.length;
          if (itemsLength > 0 && itemsLength >= this.pagination.pageSize) {
            this.pagination.currentPage = this.pagination.currentPage + 1;
          }
          if (itemsLength == 0 || itemsLength < this.pagination.pageSize) {
            this.pagination.lastRow = this.pagination.currentPage * this.pagination.pageSize + itemsLength;
          }
          this.loadingTotal = this.pagination.lastRow !== -1 ? this.pagination.lastRow : params.request.endRow;
          params.successCallback(items.content, this.pagination.lastRow);
          if (itemsLength === 0 && this.pagination.lastRow <= 0)
            if (items.hasOwnProperty('msg')) {
              this.msg.info(items.msg);
            } else {
              this.msg.info(`未找到满足条件的数据`);
            }

        } else {
          params.successCallback([], 0);
        }
        this.gridApi.hideOverlay();
        this.searchLoading = false;
      });
  }

  destroyModal(): void {
    this.modal.destroy(this.resultData);
  }

  _search(): void {
    // 将分页器的数值改为初始数值
    this.total = 0;
    this.currentPage = 0;
    this.pageTotal = 0;
    this.pagination.currentPage = 0;
    this.pagination.lastRow = -1;

    this.searchLoading = true;

    if (this.checkboxSelect) {
      this.clientSideQueryData();
    } else {
      this.queryData();
    }
  }

  private queryData() {
    this.conditionRequired = false;
    const conditionList = this.getConditionList(this.showConditionField);

    // 检查必填条件不输入情况下不给查询
    if (this.conditionRequired) {
      this.searchLoading = false;
      return;
    }
    //, size: this.pageSize, page: this.currentPage - 1
    let sendData = { condition: conditionList };

    if (this.domain) {
      sendData['domain'] = this.domain;
    }

    if (this.apiParams) {
      sendData = { ...sendData, ...this.apiParams };
    }
    if (this.conditionModel) {
      sendData['conditionModel'] = this.conditionModel;
    }

    // TODO 检查返回值是否不为空数组
    if (this.treeData || this.rowModelType == 'clientSide') {
      this.gridApi.showLoadingOverlay();
      this.apiService.post(this.api, { 'body': JSON.stringify(sendData) }).subscribe(
        (body) => {
          if (body) {
            this.total = body.total;
            this.pageTotal = body.pages;
            let tempRowData: any;
            if (this.treeData === true) {
              tempRowData = body;
            } else {
              tempRowData = body.content;
            }

            this.rowData = [];
            this.gridOptions.api.setRowData(tempRowData);
            this.rowData = tempRowData;


            if (this.rowData.length === 0) this.msg.info(`未找到满足条件的数据`);
          }
          this.autoSizeAll();
          this.searchLoading = false;
          this.gridApi.hideOverlay();
        });
    } else {
      let dataSource = {
        rowCount: null,
        getRows: (params: any) => this.getRows(params, [], sendData),
      };
      //this.gridApi.setDatasource(dataSource);
      this.gridApi.setServerSideDatasource(dataSource);
    }

  }


  private clientSideQueryData(page?) {
    this.conditionRequired = false;
    const conditionList = this.getConditionList(this.showConditionField);

    // 检查必填条件不输入情况下不给查询
    if (this.conditionRequired) {
      this.searchLoading = false;
      return;
    }
    //, size: this.pageSize, page: this.currentPage - 1
    let sendData = { condition: conditionList };

    if (this.domain) {
      sendData['domain'] = this.domain;
    }

    if (this.apiParams) {
      sendData = { ...sendData, ...this.apiParams };
    }
    if (this.conditionModel) {
      sendData['conditionModel'] = this.conditionModel;
    }

    sendData['size'] = this.pageSize;
    sendData['page'] = this.pagination.currentPage;
    if (page) {
      sendData['page'] = this.pagination.currentPage - 1;
    }
    this.gridApi.showLoadingOverlay();
    this.apiService.post(this.api, { 'body': JSON.stringify(sendData) }).subscribe(
      (body) => {
        if (body) {
          this.total = body.total;
          if (body.size) this.pageSize = body.size;
          this.pageTotal = body.pages;
          const tempRowData: any[] = body.content;

          this.rowData = [];
          this.gridOptions.api.setRowData(tempRowData);
          this.rowData = tempRowData;

          setTimeout(() => {
            let uniqueKey = this.uniqueKey;
            this.gridApi.forEachNode((node) => {
              let check = false;
              let primaryKey = node.data[uniqueKey];
              this.resultsData.forEach((res) => {
                if (res[uniqueKey] == primaryKey) {
                  check = true;
                }
              });
              if (check) {
                node.setSelected(check);
              }
            });
          }, 100);

          if (this.rowData.length === 0) this.msg.info(`未找到满足条件的数据`);
        }
        this.autoSizeAll();
        this.searchLoading = false;
        this.gridApi.hideOverlay();
      });
  }

  public contextMenuData(sendData: any) {
    let data = { data: sendData['params'], key: sendData['key'] };
    this.apiService.post(this.api, data).subscribe(
      (body) => {
        if (body) {
          // this.total = body.total;
          // this.pageTotal = body.pages;
          this.rowData = [];
          this.rowData = body;
          this.gridOptions.api.setRowData(this.rowData);
          if (this.rowData.length === 0) {
            this.msg.info(`未找到满足条件的数据`);
            setTimeout(() => {
              this.modal.close();
            }, 1000);
          }
        }
        this.autoSizeAll();
        // this.searchLoading = false;
      });
  }

  onSelectionChanged() {
    if (this.rowSelection != 'single' && !this.checkboxSelect) {
      return;
    }

    if (this.checkboxSelect) {
      if (!this.rowData) return;
      let uniqueKey = this.uniqueKey;

      let resultsData = this.resultsData.filter((res) => {
          let check = true;
          this.rowData.forEach((row) => {
            if (res[uniqueKey] == row[uniqueKey]) {
              check = false;
            }
          });
          return check;
        },
      );

      this.resultsData = resultsData;

      const selectedRow = this.gridOptions.api.getSelectedRows();

      selectedRow.forEach((row) => {
        let primaryKey = row[uniqueKey];
        let check = true;
        if (!this.addSame) {
          resultsData.forEach((res) => {
            if (res[uniqueKey] == primaryKey) {
              check = false;
            }
          });
        }
        if (check) {
          if (this.secondaryApi !== '') {
            this.secondaryQueryS(row);
          } else {
            this.resultsData.push(row);
          }
        }

      });

    } else {
      const selectedRow = this.gridOptions.api.getSelectedRows();
      let check = true;
      if (!this.addSame) {
        let uniqueKey = this.uniqueKey;
        let primaryKey = selectedRow[0][uniqueKey];
        this.gridData.forEach((res) => {
          if (res[uniqueKey] == primaryKey) {
            check = false;
          }
        });
      }

      if (check) {
        if (this.secondaryApi !== '') {
          this.secondaryQuery(selectedRow, 'select');
        } else {
          this.resultData = selectedRow;
          // this.loading = false;
        }
      } else {
        this.msg.error('不允许重复选择');
      }
    }

  }

  resetForm() {
    this.form.reset();
    this.subject.publish(this.ctx, 'defaultValue', 'test');
    this.subject.publish(this.ctx, 'resetForm', 'test');
  }

  getDataPath(data) {
    return data.path.split('/'); // path: "Erica/Malcolm"
  }

  onFilterTextBoxChanged() {
    let data = this.form.value['quickSearchInput'];
    this.searchSubject.next(data);
  }

  onRowClicked() {
    if (this.rowSelection !== 'multiple' || this.checkboxSelect) {
      return;
    }

    let uniqueKey = this.uniqueKey;
    const selectedRow = this.gridOptions.api.getSelectedRows();
    let primaryKey = selectedRow[0][uniqueKey];
    let check = true;
    if (!this.addSame) {
      this.resultsData.forEach((res) => {
        if (res[uniqueKey] == primaryKey) {
          check = false;
        }
      });
    }

    if (check) {
      if (this.secondaryApi !== '') {
        this.secondaryQuery(selectedRow, 'click');
      } else {
        this.resultsData.push(selectedRow[0]);
      }
    } else {
      this.msg.error('不允许重复选择');
    }
  }

  queryTime: any;

  secondaryQuery(selectedRow: any, status: any) {
    let sendData = {};
    if (this.treeData) {
      sendData = { 'id': selectedRow[0].id };
    } else {
      if (this.checkboxSelect) {
        sendData = { condition: selectedRow };
      } else {
        sendData = { condition: selectedRow[0] };
      }
    }

    if (this.conditionModel) {
      sendData['conditionModel'] = this.conditionModel;
    }

    if (!this.checkboxSelect) {
      clearTimeout(this.queryTime);
      if (status == 'select') {
        this.resultData = '';
      }
    }


    this.queryTime = setTimeout(() => {
      this.apiService.post(this.secondaryApi, sendData).subscribe((result) => {
        if (result) {
          let check = true;
          if (!this.addSame) {
            let uniqueKey = this.uniqueKey;
            let primaryKey = result[uniqueKey];
            this.gridData.forEach((res) => {
              if (res[uniqueKey] == primaryKey) {
                check = false;
              }
            });
            this.resultsData.forEach((res) => {
              if (res[uniqueKey] == primaryKey) {
                check = false;
              }
            });
          }
          if (check) {
            if (status == 'select') {
              if (this.checkboxSelect) {
                this.resultsData.push(result);
              } else {
                this.resultData = { ...result };
              }
            } else if (status == 'click') {
              this.resultsData.push(result);
            } else if (status == 'doubleClick') {
              this.resultData = { ...result };
              this.destroyModal();
            }
          } else {
            this.msg.error('不允许重复选择');
          }
        }
      });
    }, 500);

  }

  secondaryQueryS(selectedRow: any) {
    let sendData = { condition: selectedRow };

    if (this.conditionModel) {
      sendData['conditionModel'] = this.conditionModel;
    }

    this.apiService.post(this.secondaryApi, sendData).subscribe((result) => {
      if (result) {
        let check = true;
        if (!this.addSame) {
          let uniqueKey = this.uniqueKey;
          let primaryKey = result[uniqueKey];
          this.gridData.forEach((res) => {
            if (res[uniqueKey] == primaryKey) {
              check = false;
            }
          });
        }
        if (check) {
          this.resultsData.push(result);
        }
      }
    });
  }

  clearResultsData(index) {
    if (this.checkboxSelect) {
      let uniqueKey = this.uniqueKey;
      this.gridApi.forEachNode((node) => {
        let primaryKey = node.data[uniqueKey];
        let check = this.resultsData[index][uniqueKey] == primaryKey;
        if (check) {
          node.setSelected(false);
        }
      });
    }
    this.resultsData.splice(index, 1);
  }

  onRowDoubleClick() {
    if (this.rowSelection !== 'single') {
      return;
    }

    let selectedRow = this.gridOptions.api.getSelectedRows();
    // console.log(this.gridData);
    if (this.selectLastStage) {
      if (!selectedRow[0][this.selectLastStage]) {
        this.msg.info('不允许选择非末级');
        selectedRow = null;
        return;
      }
    }
    if (this.secondaryApi !== '') {
      this.secondaryQuery(selectedRow, 'doubleClick');
    } else {
      this.resultData = selectedRow;
      this.destroyModal();
    }

  }

  onPageIndexChange() {
    this.clientSideQueryData(true);
    // this.queryData();
  }

  onPageSizeChange(num) {
    // console.log(num);
    this.pageSize = num;
    this.pagination.currentPage = 0;
    this.clientSideQueryData();
  }

  /**
   * 功能：拼接查询条件
   * @returns {any[]}
   */
  getConditionList(conditionField: any): any[] {
    let conditionList = [];
    for (const tempConditionField of conditionField) {
      let fieldKey = tempConditionField.key;
      const fieldValue = this.model[fieldKey];

      const config = tempConditionField.templateOptions.config;
      const required = config.required;

      // 判断查询的操作条件（=、like...）
      let operatorValue = '';
      if (config.value) {
        operatorValue = config.value;
      } else if (config.operators.length > 0) {
        operatorValue = config.operators[0];
      }
      // 判断是否必填
      if (required && !exists(fieldValue)) {
        this.msg.error(`${tempConditionField.templateOptions.label}为必填项`, { apesDuration: 5000 });
        conditionList = [];
        this.conditionRequired = true;
        break;
      }

      if (!exists(fieldValue) || fieldValue.length == 0) {
        continue;
      }

      // 处理存在明细表字段的情况
      fieldKey = replaceAll(fieldKey, '#', '.');

      if (config.type === 'dateRange') {
        const dataModelStar = {
          field: fieldKey,
          operator: 'GTE',
          value: dateFormat('yyyy-MM-dd', fieldValue[0]) + ' 00:00:00',
          type: 'date',
        };
        const dataModelEnd = {
          field: fieldKey,
          operator: 'LTE',
          value: dateFormat('yyyy-MM-dd', fieldValue[1]) + ' 23:59:59',
          type: 'date',
        };

        conditionList.push(dataModelStar);
        conditionList.push(dataModelEnd);
      } else if (config.type === 'date') {
        const dataModel = { type: 'date' };

        dataModel['field'] = fieldKey;
        dataModel['operator'] = operatorValue ? operatorValue : 'EQ';
        dataModel['value'] = dateFormat('yyyy-MM-dd', fieldValue);
        conditionList.push(dataModel);
      } else {
        const dataModel = {};

        dataModel['field'] = fieldKey;
        dataModel['operator'] = operatorValue ? operatorValue : 'EQ';
        dataModel['value'] = type(fieldValue) == 'string' ? fieldValue.trim() : fieldValue;
        conditionList.push(dataModel);
      }
    }

    return conditionList;
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.agGrid = params;
    this.gridColumnApi = params.columnApi;
    //this.autoSizeAll();
    this.agGrid.api = params.api;

    // const dataSource = this.getDataSource();
    // this.agGrid.api.setDatasource(dataSource);


    // let server = new FakeServer(data);
    // let datasource = new ServerSideDatasource(server);
    // params.api.setServerSideDatasource(datasource);
  }


  sizeToFit() {
    this.gridApi.sizeColumnsToFit();
  }

  autoSizeAll() {
    let allColumnIds = [];
    this.gridColumnApi.getAllColumns().forEach(function(column) {
      allColumnIds.push(column.colId);
    });
    this.gridColumnApi.autoSizeColumns(allColumnIds);
  }

  getValueFormatter(): string {
    return this.valueFormatter || 'value.name';
  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      value: value,
    });
  }

}

